package cn.iocoder.yudao.module.tms.job;

import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.tms.dal.dataobject.companyaccountperiod.CompanyAccountPeriodDO;
import cn.iocoder.yudao.module.tms.dal.mysql.companyaccountperiod.CompanyAccountPeriodMapper;
import cn.iocoder.yudao.module.tms.service.accountperiodtodo.AccountPeriodTodoService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * 账期待办事项定时任务
 * 
 * 每天定时检查所有账期，生成相应的待办事项
 *
 * @author 芋道源码
 */
@Component
@Slf4j
public class AccountPeriodTodoJob implements JobHandler {

    @Resource
    private CompanyAccountPeriodMapper accountPeriodMapper;
    
    @Resource
    private AccountPeriodTodoService accountPeriodTodoService;

    @Override
    public String execute(String param) throws Exception {
        log.info("[execute] 开始执行账期待办事项检查任务");
        
        // 查询所有活跃的账期
        List<CompanyAccountPeriodDO> accountPeriods = accountPeriodMapper.selectList();
        
        int totalCount = 0;
        int successCount = 0;
        int failCount = 0;
        
        for (CompanyAccountPeriodDO accountPeriod : accountPeriods) {
            totalCount++;
            try {
                // 检查并生成待办事项
                accountPeriodTodoService.checkAndGenerateTodos(accountPeriod);
                successCount++;
            } catch (Exception e) {
                failCount++;
                log.error("[execute] 检查账期待办失败: periodId={}, companyId={}", 
                    accountPeriod.getId(), accountPeriod.getCompanyId(), e);
            }
        }
        
        String result = String.format("账期待办检查完成: 总数=%d, 成功=%d, 失败=%d", 
            totalCount, successCount, failCount);
        log.info("[execute] {}", result);
        
        return result;
    }
}
